


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;

public class TCPReceiver extends Thread{
	private Client client;
	private Socket socket;
	private boolean connected = true;
	public TCPReceiver(Client clientConnection, Socket socket){
		this.client = clientConnection;
		this.socket = socket;
	}

	@Override
	public void run(){
		BufferedReader inFromClient;
		try {
			//Incoming data stream
			inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			inFromClient.ready();
			while(connected){
				//Keep receiving data from the client in a loop.
				receive(inFromClient);
			}
		} catch (Exception e) {
			System.out.println("A client lost connection to the server.");
			connectionLost();
		}
	}

	private void connectionLost(){
		//System.out.println("Connection lost with " + client.getName());
		connected = false;
		this.client.disconnect();
	}

	/**
	 * Receives the next line of data from the client.
	 * @param inputReader
	 */
	private void receive(BufferedReader inputReader){
		try{
			String receivedData = inputReader.readLine();
			processData(receivedData);
		}catch(Exception e){connectionLost();}
	}

	/**
	 * Processes incoming data.
	 * @param data Incoming data.
	 */
	private void processData(String data){
		String[] splitData = data.split("_");
		if(splitData.length > 0){ // > 1 bij de meesten??????????????????????????????????????????????????
			if(splitData[0].equals("1")){ //Ping response
				int pingId = Integer.parseInt(splitData[1]);
				ConnectionHandler.getInstance().getPinger().receivePing(this.client, pingId);
			}
			else if(splitData[0].equals("2")){ //Client has just connected and is sending its data
				String playername = splitData[1];
				String playerwebid = "";
				//If webId is sent, store that too.
				if(splitData.length > 2)
					playerwebid = splitData[2];
				ConnectionHandler.getInstance().processNewClientData(this.client, playername, playerwebid); //Share its data with the other clients.
			}
			else if(splitData[0].equals("5")){ //Ready state has changed for this client
				ConnectionHandler.getInstance().clientLobbyReadyStatusChanged(this.client, splitData[1]);
			}
			else if(splitData[0].equals("6")){ //Client has finished loading the level
				ConnectionHandler.getInstance().clientHasFinishedLoading(this.client);
			}
			else if(splitData[0].equals("21") || splitData[0].equals("22")){ //Client has fired a bullet
				spawnBullet(splitData);
			}
			else if(splitData[0].equals("99")){ //Client has finished loading the level
				try
				{
					int port = Integer.parseInt(splitData[1]);
					this.client.setClientUdpPort(port);
				}
				catch (Exception e) {}
			}
		}
	}

	public void notifyTimeOut(){
		System.out.println(this.client.getName() + " timed out. Shutting down this connection.");
		connectionLost();
	}

	/**
	 * Spawns a projectile.
	 * @param splitData
	 */
	private void spawnBullet(String[] splitData){
		if(splitData.length == 7){ //validate data length
			new ThreadedBulletProcessor(splitData, this.client).start();
			
//			try{
//				String bulletType = splitData[1];
//				float spawnX = Float.parseFloat(replaceCommaByDot(splitData[2]));
//				float spawnY = Float.parseFloat(replaceCommaByDot(splitData[3]));
//				float directionX = Float.parseFloat(replaceCommaByDot(splitData[4]));
//				float directionY = Float.parseFloat(replaceCommaByDot(splitData[5]));
//				float speed = Float.parseFloat(replaceCommaByDot(splitData[6]));
//
//				Bullet newBullet = new Bullet(bulletType, spawnX, spawnY, directionX, directionY, speed);
//				this.client.getPlayerData().addBullet(newBullet);
//				
//				String pingAdaptedSpawnX = String.valueOf((int)newBullet.getPingAdaptedSpawnPositionX(this.client));
//				String pingAdaptedSpawnY = String.valueOf((int)newBullet.getPingAdaptedSpawnPositionY(this.client));
//				ConnectionHandler.getInstance().sendToAllClients("21_" + newBullet.getId() + "_" + newBullet.getType() + "_" 
//						+ pingAdaptedSpawnX + "_" + pingAdaptedSpawnY + "_" + splitData[4] + "_" + splitData[5]);
//			}
//			catch(Exception e){
//				System.out.println("Could not create bullet: " + e);
//			}
		}
		else System.out.println("Bullet data is invalid.");
	}
	
	private String replaceCommaByDot(String stringToCheck){
		String result = stringToCheck;
		result = result.replace(',', '.');
		return result;
	}
}
